package algorithm.disjoint.union;

import java.util.Arrays;

/**
 * 项目名称: god
 * 包 名 称: algorithm.disjoint.union
 * 类 名 称: UnionFindQuickUnionRank
 * 类 描 述: TODO
 * 创建时间: 2020/6/30 1:33 下午
 * 创 建 人: Justice
 * 基于rank的优化
 */
public class UnionFindQuickUnionRank extends UnionFindQuickUnion {
    private int[] ranks;

    public UnionFindQuickUnionRank(int capacity) {
        super(capacity);
        ranks = new int[capacity];
        Arrays.fill(ranks, 1);
    }

    public void union(int v1, int v2) {
        int p1 = find(v1);
        int p2 = find(v2);
        if (p1 == p2) return;
        if (ranks[p1] < ranks[p2]) {
            parents[p1] = p2;
        } else if (ranks[p1] > ranks[p2]) {
            parents[p2] = p1;
        } else {
            parents[p1] = p2;
            ranks[p2] += 1;
        }
    }
}
